package com.sushuo.api.service;

import java.util.LinkedList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.sushuo.api.dao.ProductDao;
import com.sushuo.base.bean.Product;
import com.sushuo.base.bean.sql.Sort;
import com.sushuo.base.bean.sql.PageData;

@Service
public class ProductService {
    
    @Autowired
    private ProductDao productDAO;
    
    public Product getById(Integer id){
        return productDAO.findOne(id);
    }
    
    public Product save(Product product){
        return productDAO.save(product);
    }
    
    public void deleteById(Integer id){
        productDAO.delete(id);
    }
    
    public PageData<Product> getPage(int page, int pageSize){
        StringBuilder sb = new StringBuilder();
        sb.append("SELECT * FROM t_product p ");
        List<Object> param = new LinkedList<>();
        return productDAO.findPageBySql(sb.toString(), param, Product.class, new PageData<>(page, pageSize),
                Sort.getSort("gmt_modified", Sort.Direction.DESC));
    }
    
    public PageData<Product> getPageByUserId(int page, int pageSize, int userId){
        StringBuilder sb = new StringBuilder();
        sb.append("SELECT * FROM t_product p WHERE p.user_id = ?1");
        List<Object> param = new LinkedList<>();
        param.add(userId);
        return productDAO.findPageBySql(sb.toString(), param, Product.class, new PageData<Product>(page, pageSize),
                Sort.getSort("gmt_modified", Sort.Direction.DESC));
    }
}
